package org.wpahs.ahn.rssfeed;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.webkit.URLUtil;

import org.wpahs.ahn.rssfeed.DB.DBFeedItem;
import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Wow Great
 * Created by dgambone on 02/24/2015.
 */
public class DownloadImage extends AsyncTask<Void, Void, String> {
    private Image mImage;
    private Context mContext;
    public DownloadImage(Context context,Image image){
        mContext = context;
        mImage = image;
    }
    @Override
    protected String doInBackground(Void... params) {
        String base64Image = null;
        try {
            URL urlConnection = new URL(mImage.getUrl());

            HttpURLConnection connection;
            if(!URLUtil.isHttpsUrl(mImage.getUrl())){
                connection = (HttpURLConnection) urlConnection
                        .openConnection();

            }else{
                connection = (HttpsURLConnection) urlConnection
                        .openConnection();
            }

            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            base64Image = encodeToBase64(myBitmap);
            //java.io.IOException, org.apache.http.client.ClientProtocolException

        }catch (Exception ex){
            Log.e(this.getClass().getName(), "downloadImage" +
                            (ex.getMessage() != null ? ex.getMessage() : "Mystery Error")
            );
        }
        return base64Image;
    }

    @Override
    protected void onPostExecute(String b64Image){
        if(b64Image != null){
            if(mImage.getDownloadType() == Downloader.DownloadType.FeedImage){
                DBMyFeed dbMyFeed = new DBMyFeed(mContext);
                try {
                    dbMyFeed.setImage(mImage.getId(),b64Image);
                    broadcastFeedImageDone(mContext,mImage.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(mImage.getDownloadType() == Downloader.DownloadType.FeedItemImage){
                DBFeedItem dbFeedItem = new DBFeedItem(mContext);
                try {
                    dbFeedItem.setImage(mImage.getSubId(),b64Image);
                    broadcastFeedItemImageDone(mContext,mImage.getId(),mImage.getSubId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Downloader.removeImageFromQueue(mImage);
    }

    private String encodeToBase64(Bitmap image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int compression = getShrinkToPercentage(image.getByteCount(),1048576); //1048576 1mb
        image.compress(Bitmap.CompressFormat.PNG, compression, os);
        byte[] b = os.toByteArray();

        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    private int getShrinkToPercentage(long bytes, long targetMaxSize){
        //get the difference first
        int dif = (int) (targetMaxSize * 100 / bytes);
        if(dif >=100){
            dif = 100;
        }
        Log.i("ImageCompress", "Image compression will be " + String.valueOf(dif));
        return dif;
    }

    private void broadcastFeedImageDone(Context context,int feedId){
        Intent intent = new Intent(RSSGetService.FEED_IMAGE_DONE);
        intent.putExtra(context.getResources().getString(R.string.feed_id), feedId);
        context.sendBroadcast(intent);
    }

    private void broadcastFeedItemImageDone(Context context,int feedId, int feedItemId){
        Intent intent = new Intent(RSSGetService.FEEDITEM_IMAGE_DONE);
        intent.putExtra(context.getResources().getString(R.string.feed_item_id), feedItemId);
        intent.putExtra(context.getResources().getString(R.string.feed_id), feedId);
        context.sendBroadcast(intent);
    }
}




